from django.db import models
from django.contrib.auth.models import User
from puppy.model import Query, Response
from puppy.query.exceptions import QueryRejectionError
from service import service
import urllib2, feedparser

class RSS(models.Model):
  name = models.CharField(max_length=100)
  url = models.CharField(max_length=255)
  users = models.ManyToManyField(User)

  def __unicode__(self):
    return "RSS feeds"

  def fetchRSS(self):
    data = urllib2.urlopen(self.url)
    return feedparser.parse(data.read())
  
class Favorites(models.Model):
  search = models.CharField(max_length=255)
  user_id = models.IntegerField()

  def __unicode__(self):
      return "gej"

class SearchEngine():
  
  def queryForNews(self, query_string, category):
    return self.query(query_string, category, 'news_search')

  def queryForVideos(self, query_string):
    
    if query_string.rfind("-") != -1:
      query_string = query_string[0:query_string.rfind("-")]

    result = self.query(query_string, '', 'video_search')
    for res in result:
      res['thumbnail'] = res.media_thumbnail[2]['url']
      res['url'] = res.links[0]['href']
    return result

  def queryForPictures(self, query_string):
    result = self.query(query_string, '', 'picture_search')
    return result

  def query(self, query_string, category, service_name):
    
    # Mix in category in query_string as appropriate
    if query_string == "":
      query_processed_string = category
    elif category != '':
      query_processed_string = query_string + " and " + category
    else:
      query_processed_string = query_string + " and " + category
    query_processed_string = query_processed_string.encode('utf8')
    # Build query
    query = Query(query_processed_string)

    # Execute query using PuppyIR
    results = {}
    try:
      results = service.search_services[service_name].search( query ).entries[0:9]
    except QueryRejectionError:
      return null

    return results
